package com.lupan.beanFactory;


import com.lupan.bean.Student;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * 说明：自定义JNDI创建工厂
 *
 * @author lupan
 * @version 2016/7/7 15:47
 */
public class StudentBeanFactory implements ObjectFactory {
    @Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
        Student student = new Student();
        Reference ref = (Reference)obj;
        Enumeration<RefAddr> address = ref.getAll();

        while (address.hasMoreElements()){
            RefAddr refAddr = address.nextElement();
            String typeName = refAddr.getType();
            String value = (String)refAddr.getContent();

            switch (typeName) {
                case "nameField":
                    student.setName(value);
                    break;
                case "numField":
                    student.setNum(value);
                    break;
                case "idField":
                    student.setId(Long.parseLong(value));
                    break;
            }
        }

        return student;
    }
}
